package driver.ui.driver;



import java.util.ArrayList;

import driver.ui.R;
import driver.ui.driver.Adapter.ContactlistAdapter;
import driver.ui.driver.Beans.notification;
import driver.ui.driver.Beans.person;
import Databasehelper.Notificationhelper;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;

import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;


import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;


import android.provider.Contacts;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

public class Contactlist extends Activity{

	private static final int HELLO_ID = 1;
	ListView contactList;
	TextView userName;
	ContactlistAdapter arrayAdapter;	
	Notificationhelper dbhelper;
	Boolean flag=false;

	 @Override
	    public void onCreate(Bundle savedInstanceState) {		 
		 	
	        super.onCreate(savedInstanceState);
	        
	        setContentView(R.layout.contacts);
	        ArrayList<String> contacts=new ArrayList();
	        //Get User Name
	        Bundle extras = getIntent().getExtras();
			String username = extras.getString("name");	
			
	        userName = (TextView) findViewById(R.id.username);
	        
	        userName.setText(username);
	        
	       
	        
	        //Integrete android contact list
	        ContentResolver cr = getContentResolver();
	        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
	                null, null, null,ContactsContract.Contacts.DISPLAY_NAME+ " ASC");
	        if (cur.getCount() > 0) {
		    while (cur.moveToNext()) {
		    	String id = cur.getString(
	                        cur.getColumnIndex(ContactsContract.Contacts._ID));
		    	String name = cur.getString(
	                        cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
		    	
		    	contacts.add(name);
		    	if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
	 		    //Query phone here.  
		    		Cursor pCur = cr.query(
		    	 		    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
		    	 		    null, 
		    	 		    ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", 
		    	 		    new String[]{id}, null);
		    	 	        while (pCur.moveToNext()) {
		    	 		    // Do something with phones
		    	 	        } 
		    	 	        pCur.close();
	 	        }
	            }
	 	}

	        
	        contactList = (ListView) findViewById(R.id.contactList);
	        ArrayList<person>   contactlist= new ArrayList<person>();

	        //Initialize our array adapter notice how it references the contactlistitems.xml layout
	        arrayAdapter = new ContactlistAdapter(Contactlist.this, R.layout.contactlistitems,contactlist);
	        
	        //Add contacts
	        person p1=new person();
	        p1.setName(contacts.get(0));
	       	p1.setImgsrc(R.drawable.a_2);
	       	p1.setStatus("Driving");
	       	contactlist.add(p1);
	       	
	        person p2=new person();
	        p2.setName(contacts.get(1));
	       	p2.setImgsrc(R.drawable.a_2);
	       	p2.setStatus("Available");

	       	contactlist.add(p2);
	       	
	       	
	        person p3=new person();
	        p3.setName(contacts.get(2));
	        p3.setImgsrc(R.drawable.a_2);
	        p3.setStatus("Offline");
	       	contactlist.add(p3);
	       	
	       	
	        person p4=new person();
	        p4.setName(contacts.get(3));
	       	p4.setImgsrc(R.drawable.a_2);       	
	       	p4.setStatus("Meeting");

	       	contactlist.add(p4);
	       	
	        person p5=new person();
	        p5.setName(contacts.get(4));
	       	p5.setImgsrc(R.drawable.a_2);
	       	p5.setStatus("Available");
	       	contactlist.add(p5);
	       	
	       	
	        person p6=new person();
	        p6.setName(contacts.get(5));
	       	p6.setImgsrc(R.drawable.a_2);
	       	p6.setStatus("Available");
	 
	       	contactlist.add(p6);
	       	
	        person p7=new person();
	        p7.setName(contacts.get(6));
	       	p7.setImgsrc(R.drawable.a_2);
	       	p7.setStatus("Available");
	       	contactlist.add(p7);
       	if(contacts!=null&&contacts.size()>7)
	       	{
	       		for(int i=7;i<contacts.size();i++)
	       		{
		       		person p=new person();
		       		p.setName(contacts.get(i));
		       	 	p.setImgsrc(R.drawable.a_2);
			       	p.setStatus("Pending");
			       	contactlist.add(p);
	       		}
	       	}
	       	
	        //Set the above adapter as the adapter of choice for our list
	        contactList.setAdapter(arrayAdapter);
	       	
	        //ListView's Listener
	        contactList.setOnItemClickListener(new OnItemClickListener(){

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int position, long arg3) {
					// TODO Auto-generated method stub
					Object listItem = contactList.getItemAtPosition(position);
					person contact=(person)listItem;
					String status=contact.getStatus();

						if(status.equals("Driving"))
						{
						 
							Intent intent = new Intent(getApplicationContext(), Contactperson.class);
							if(contact!=null)
							intent.putExtra("name",contact.getName() );
					        startActivity(intent);
					        
							
						}
						else if(status.equals("Meeting"))
						{
						 	
						 	Intent intent=new Intent();
						 	if(contact!=null)
						 	intent.putExtra("name",contact.getName() );
						 	intent.setAction("Contactmeeting");
						 	startActivity(intent);
						}
						else if(status.equals("Available"))
						{
							Intent intent=new Intent();
							if(contact!=null)
							intent.putExtra("name",contact.getName() );
							intent.setAction("Contactavailable");
							startActivity(intent);
						}
										
				}});

	
	        //Status Spinner
	    	Spinner spinner = (Spinner) findViewById(R.id.spinner);
	        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
	                this, R.array.status_array, android.R.layout.simple_spinner_item);
	        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        spinner.setAdapter(adapter);

				
	        //Get Notifications	       
	        ArrayList<notification> nots=new ArrayList();
	        dbhelper=new Notificationhelper(this);
	        String[] usernames=userName.getText().toString().split(" ");
	        if(usernames.length>1)
	        nots=dbhelper.getAllNotByTo(usernames[0]+usernames[1]);
	        //Send Notifications
	        if(flag==false&&nots.size()>0)
	        {
	       
	        	notification not;
	        	not=nots.get(0);
		        String ns = Context.NOTIFICATION_SERVICE;
		        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
		        int icon = R.drawable.notification_icon;        // icon from resources
		        long when;
		        CharSequence tickerText;
		        Context context;
		        CharSequence contentTitle;
		        CharSequence contentText;
		        PendingIntent contentIntent;
		        Notification notification;
		        if(not.getType().equals("notification"))
		        {
			        tickerText = "Pickup Setting";              // ticker-text
			         when= System.currentTimeMillis();         // notification time
			        context = getApplicationContext();      // application Context
			        contentTitle = "Pick up with "+not.getSentfrom()+not.getSentto();  // expanded message title
			         contentText = "Tap to confirm details";      // expanded message text
		
			        Intent notificationIntent = new Intent();
			        notificationIntent.setAction("Pickupdetail");
			        notificationIntent.putExtra("to",not.getSentto());
			        notificationIntent.putExtra("from",not.getSentfrom());
			        
			        notificationIntent.putExtra("username", userName.getText().toString());
			  
			        contentIntent = PendingIntent.getActivity(context, 0 , notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

			       
		        	
		        }
		        else
		        {
		        	tickerText = "Confirmation";              // ticker-text
			        when = System.currentTimeMillis();         // notification time
			        context = getApplicationContext();      // application Context
			        contentTitle = "Pick Up Confirmation from "+not.getSentfrom();  // expanded message title
			        contentText = "Tap to confirm details";      // expanded message text
			        
			        Intent notificationIntent = new Intent();
			        notificationIntent.setAction("Pickupconfirm");
			        notificationIntent.putExtra("to",not.getSentto());
			        notificationIntent.putExtra("from",not.getSentfrom());
			        notificationIntent.putExtra("username", userName.getText().toString());
			        contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
			     
		        }
	
	
		        flag=true;
		     // the next two lines initialize the Notification, using the configurations above
		        notification = new Notification(icon, tickerText, when);
		        

		        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
		        notification.flags |= Notification.FLAG_AUTO_CANCEL;
		        mNotificationManager.notify(1, notification);
		        
	       
	        }
	        


	 }


public void homepageClicked(View view)
{

	Intent intent=new Intent();
	intent.putExtra("name",userName.getText().toString());	
	intent.setAction("Contactavailable");
	startActivity(intent);
	}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.addcon:
    {
	 	Intent addIntent=new Intent();
	 	addIntent.setAction("Addnewcontact");
	 	startActivity(addIntent);
    	
    }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}




}
